package com.whzm.service.Impl;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.whzm.mapper.ConfigurationMapper;
import com.whzm.service.PhoneService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PhoneServiceImpl implements PhoneService {
    @Autowired
    private RedisServiceImpl redisService;

    @Autowired
    private ConfigurationMapper configurationMapper;

    /**
     * 发送一条验证码给某一个电话号码
     * @param phone
     * @param code
     * @return
     */
    @Override
    public String sendPhoneMsg(String phone,String code) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", configurationMapper.selectByName("accessKeyId"),
                configurationMapper.selectByName("secret"));
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", configurationMapper.selectByName("SignName"));
        request.putQueryParameter("TemplateCode", configurationMapper.selectByName("TemplateCode"));
        request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");


        try {
            CommonResponse response = client.getCommonResponse(request);
            //该验证码有效期为三分钟
            redisService.set("p" + phone,code,(long)3*60);
        }  catch (Exception e) {
            e.printStackTrace();
        }

        return "发送成功";
    }
}
